<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>基本资料</span>
    </div>
    <!-- 表单 -->
    <el-form :model="user" label-width="80px" :rules="userRules" ref="userRef">
      <!-- 登录名称 -->
      <el-form-item label="登录名称">
        <el-input v-model="user.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="user.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="user.email"></el-input>
      </el-form-item>
      <!-- 按钮 -->
      <el-form-item>
        <el-button type="primary" @click="updateUserInfo">提交修改</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { updateUserAPI } from '@/api/user.js'
export default {
  name: 'UserInfo',
  data() {
    return {
      // 数据对象
      user: Object.assign({}, this.$store.state.user),
      userRules: {
        nickname: [
          { required: true, message: '请输入用户昵称', trigger: 'blur' },
          { pattern: /^\S{1,10}$/, message: '昵称必须是1-10位的非空字符串', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    updateUserInfo() {
      this.$refs.userRef.validate(async valid => {
        if (!valid) return
        // console.log('发请求')
        const { data: res } = await updateUserAPI(this.user)
        if (res.code === 0) {
          this.$message.success(res.message)
          this.$store.dispatch('initUser')
        } else {
          this.$message.error(res.message)
        }
        // console.log(res)
      })
    },
    // 重置 把 vuex 中的数据，重新绑定为 form 表单的数据源
    reset() {
      this.user = Object.assign({}, this.$store.state.user)
      this.$refs.userRef.clearValidate()
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
</style>
